﻿using Chat.Common;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatServerLib
{
    public class ONE2ONE : CommandBase<ChatSession, StringRequestInfo>
    {
        /// <summary>
        /// 一对一发消息
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        public override void ExecuteCommand(ChatSession session, StringRequestInfo requestInfo)
        {
            string body = requestInfo.Body;
            try
            {
                body = Base64.Decode(body);
            }
            catch { }
            session.Logger.DebugFormat("Got command: {0}=>{1}", requestInfo.Key, body);

            ResultStatus rs = new ResultStatus(ResultType.SEND);

            if (string.IsNullOrWhiteSpace(session.UserName))
            {
                rs.Success = false;
                rs.Message = "You are not JOIN yet.";
                session.Send(rs.ToString());
                return;
            }

            if (string.IsNullOrWhiteSpace(body))
            {
                rs.Success = false;
                rs.Message = "Pick one user to send.";
                session.Send(rs.ToString());
                return;
            }

            string toUserName = body.Substring(0, body.IndexOf(' '));
            string message = body.Substring(body.IndexOf(' '));

            var toSession = session.AppServer.GetSessions(_ => _.UserName.Equals(toUserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (toSession == null)
            {
                rs.Success = false;
                rs.Message = string.Format("User [{0}] is not online.", toUserName);
                session.Send(rs.ToString());
                return;
            }

            rs.Type = ResultType.RECEIVE;
            rs.Message = string.Format("[{0}] {1}", session.UserName, message);
            toSession.Send(rs.ToString());
        }
    }
}
